package com.zhuiyun.project.api.system.register.service.Impl;

import com.zhuiyun.project.api.system.register.service.RegisterService;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.mapper.SysUserMapper;
import com.zhuiyun.project.api.system.user.service.SysUserService;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.security.commonhandler.SecurityLoginUserVerification;
import com.zhuiyun.project.utils.RedisCache;
import com.zhuiyun.project.utils.constants.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName RegisterServiceImpl
 * @Description TODO
 * @Author Administrator
 * @Date 2023/11/3 8:59
 **/@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public CommonResult userRegister(SysUser sysUser, String emailCode) throws Exception {
        SecurityLoginUserVerification.vitParams(sysUser.getLoginName(),EmErrorCode.USERNAME_IS_NULL.getErrMsg());
        // 1、查询全部用户名 与前端传过来的值对比，如果相同，返回 用户名已存在
        SysUser userByLoginName = userService.getUserByLoginName(sysUser.getLoginName());
        if (userByLoginName != null){
            return CommonResult.error("用户名已存在");
        }
        SecurityLoginUserVerification.vitParams(sysUser.getEmail(),EmErrorCode.EMAIL_IS_NULL.getErrMsg());
        SysUser userByEmailAccount = userService.getUserByEmailAccount(sysUser.getEmail());
        if (userByEmailAccount != null){
            return CommonResult.error("邮箱已注册");
        }
        SecurityLoginUserVerification.vitParams(sysUser.getPhone(),EmErrorCode.PHONE_IS_NULL.getErrMsg());
        SysUser userByPhoneAccount = userService.getUserByPhoneAccount(sysUser.getPhone());
        if (userByPhoneAccount != null){
            return CommonResult.error("手机号已存在");
        }
        SecurityLoginUserVerification.vitParams(emailCode,EmErrorCode.PASSWORD_IS_NULL.getErrMsg());
        String key = CommonConstants.CACHE_EMAIL_CODE + emailCode;
        redisCache.hasKey(key);
        if (emailCode.equals(key)){
            return CommonResult.error("验证码错误，不存在");
        }
        //注册
        sysUser.setDelFlag("0");
        sysUser.setStatus("0");
        int i = userMapper.addUser(sysUser);
        if (i > 0) {
            return CommonResult.ok("注册成功！");
        }
        return CommonResult.error("注册失败！");
    }
}
